package com.xmtlxx.tms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.tms.domain.LinePoi;
import com.xmtlxx.tms.domain.Lines;
import com.xmtlxx.tms.domain.bo.LinesBo;
import com.xmtlxx.tms.domain.vo.LinePoiVo;
import com.xmtlxx.tms.domain.vo.LinesVo;
import com.xmtlxx.tms.mapper.CarrierMapper;
import com.xmtlxx.tms.mapper.LinePoiMapper;
import com.xmtlxx.tms.mapper.LinesMapper;
import com.xmtlxx.tms.service.ILinesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 线路Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class LinesServiceImpl implements ILinesService {

    private final LinesMapper baseMapper;

    private final LinePoiMapper linePoiMapper;

    private final CarrierMapper carrierMapper;
    /**
     * 查询线路
     *
     * @param id 线路主键
     * @return 线路
     */
    @Override
    public LinesVo queryById(String id){
        //return baseMapper.selectVoById(id);
        return baseMapper.selectLinesVoByID(id);
    }

    /**
     * 查询线路列表
     *
     * @param bo 线路
     * @return 线路
     */
    @Override
    public TableDataInfo<LinesVo> queryPageList(LinesBo bo, PageQuery pageQuery) {
       // LambdaQueryWrapper<Lines> lqw = buildQueryWrapper(bo);
       // Page<LinesVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<LinesVo> result = baseMapper.selectPageLinesList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询线路列表
     *
     * @param bo 线路
     * @return 线路
     */
    @Override
    public List<LinesVo> queryList(LinesBo bo) {
       // LambdaQueryWrapper<Lines> lqw = buildQueryWrapper(bo);
       // return baseMapper.selectVoList(lqw);
        return baseMapper.selectLinesList(bo);
    }

    private LambdaQueryWrapper<Lines> buildQueryWrapper(LinesBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Lines> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierId()), Lines::getCarrierId, bo.getCarrierId());
        lqw.eq(bo.getDeptId() != null, Lines::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Lines::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), Lines::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Lines::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), Lines::getCreateBy, bo.getCreateBy());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            Lines::getCreateTime ,params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Lines::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增线路
     *
     * @param bo 线路
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(LinesBo bo) {
        Lines add = BeanUtil.toBean(bo, Lines.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setDeptId(carrierMapper.selectById(add.getCarrierId()).getDeptId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        if(bo.getLinePois() != null && bo.getLinePois().size() > 0){
            int seq = 2;
            for (LinePoiVo poi :bo.getLinePois()){
                if(StringUtils.isEmpty(poi.getId())){
                    poi.setId(IdUtil.simpleUUID());
                }
                poi.setDelFlag("0");
                poi.setLineId(add.getId());

                if(poi.getType().equals("0")){
                    poi.setSeq(1);
                }
                else if(poi.getType().equals("2")){
                    poi.setSeq(bo.getLinePois().size());
                }
                else {
                    poi.setSeq(seq);
                    seq++;
                }

                if(poi.getDispatchId() == null){
                    poi.setDispatchId(add.getDispatchId());
                }

                if(poi.getPickupId() == null){
                    poi.setPickupId(add.getPickupId());
                }

                LinePoi linePoi = new LinePoi();
                BeanUtil.copyProperties(poi,linePoi);
                linePoiMapper.insertOrUpdate(linePoi);
            }
        }


        return flag;
    }

    /**
     * 修改线路
     *
     * @param bo 线路
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(LinesBo bo) {
        Lines update = BeanUtil.toBean(bo, Lines.class);
        validEntityBeforeSave(update);
        update.setDeptId(carrierMapper.selectById(update.getCarrierId()).getDeptId());
        if(bo.getLinePois() != null && bo.getLinePois().size() > 0){
            int seq = 2;
            for (LinePoiVo poi :bo.getLinePois()){
                if(StringUtils.isEmpty(poi.getId())){
                    poi.setId(IdUtil.simpleUUID());
                }
                poi.setDelFlag("0");
                poi.setLineId(update.getId());

                if(poi.getType().equals("0")){
                    poi.setSeq(1);
                }
                else if(poi.getType().equals("2")){
                    poi.setSeq(bo.getLinePois().size());
                }
                else {
                    poi.setSeq(seq);
                    seq++;
                }

                if(poi.getDispatchId() == null){
                    poi.setDispatchId(update.getDispatchId());
                }

                if(poi.getPickupId() == null){
                    poi.setPickupId(update.getPickupId());
                }

                LinePoi linePoi = new LinePoi();
                BeanUtil.copyProperties(poi,linePoi);
                linePoiMapper.insertOrUpdate(linePoi);
            }
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Lines entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除线路
     *
     * @param ids 需要删除的线路主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<LinesVo> selectLinesByClientId(LinesBo lines) {
        return baseMapper.selectLinesByClientId(lines);
    }
}
